import asyncio
from asyncio import CancelledError


async def delay(seconds):
    print(f"sleep for {seconds} seconds")
    await asyncio.sleep(seconds)


async def every_second():
    for i in range(2):
        await asyncio.sleep(1)
        print("我正在运行其他的东西...")


async def main():
    # 使用一个任务
    # sleep_for_three = asyncio.create_task(delay(3))
    # sleep_for_more = asyncio.create_task(delay(3))
    # print("开始沉睡3秒")
    # await every_second()
    # await sleep_for_three
    # await sleep_for_more
    # print("结束了")
    # 手动取消一个任务
    # long_task = asyncio.create_task(delay(10))
    #
    # t = 0
    #
    # while not long_task.done():
    #     print("任务未完成，一秒钟内检查一次")
    #     await asyncio.sleep(1)
    #     t = t + 1
    #     if t == 5:
    #         long_task.cancel()
    #
    # try:
    #     await long_task
    # except CancelledError:
    #     print("5s中未完成，任务取消")

    # await_for取消任务
    # delay_task = asyncio.create_task(delay(2))
    # try:
    #     result = await asyncio.wait_for(delay_task, timeout=1)
    #     print(result)
    # except asyncio.exceptions.TimeoutError:
    #     print(f"超时，任务是否取消？{delay_task.cancelled()}")

    # shield 保护任务免于取消
    delay_task = asyncio.create_task(delay(2))
    try:
        result = await asyncio.wait_for(asyncio.shield(delay_task), timeout=1)
        print(result)
    except asyncio.exceptions.TimeoutError:
        print(f"超时，任务是否取消？{delay_task.cancelled()}")
        result = await delay_task
        print(result)


asyncio.run(main())
